/*************************************************************************
	> File Name: 4.387D.cpp
	> Author: hug
	> Mail: hug@haizeix.com
	> Created Time: 四  2/13 08:44:51 2025
 ************************************************************************/

#include <iostream>
#include <queue>
using namespace std;

// 上下:0 左右:1

struct Data {
    int x, y, c, h;
};

int n, m;
int sx, sy, fx, fy;
char g[1005][1005];
int vis[1005][1005][2];
int dir[4][2] = {
    {-1, 0}, {1, 0}, {0, -1}, {0, 1}
};

int bfs() {
    queue<Data> q;
    q.push({sx, sy, 0, 0});
    q.push({sx, sy, 0, 1});
    vis[sx][sy][0] = vis[sx][sy][1] = 1;
    while (!q.empty()) {
        Data cur = q.front();
        q.pop();
        if (cur.x == fx && cur.y == fy) return cur.c;
        for (int i = 0; i < 4; i++) {
            if (i / 2 == cur.h) continue;
            int dx = cur.x + dir[i][0];
            int dy = cur.y + dir[i][1];
            if (dx < 0 || dx >= n || dy < 0 || dy >= m) continue;
            if (g[dx][dy] != '.') continue;
            if (vis[dx][dy][i / 2]) continue;
            vis[dx][dy][i / 2] = 1;
            q.push({dx, dy, cur.c + 1, i / 2});
        }
    }
    return -1;
}

int main() {
    cin >> n >> m;
    for (int i = 0; i < n; i++) cin >> g[i];
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < m; j++) {
            if (g[i][j] == 'S') sx = i, sy = j, g[i][j] = '.';
            if (g[i][j] == 'G') fx = i, fy = j, g[i][j] = '.';
        }
    }
    cout << bfs() << endl;
    return 0;
}
